<?php
// This function mails the contents of the log directory for the given product
function log_send($machineid,$productname=null)
{
	$target_base = '';
	if($productname!=null)
		$target_base .= io_get_product_dir($productname,null);
	$target_base .= "logs/";
	$files = glob($target_base."*.log");
	foreach($files as $file) {
		$contents = "This script was initiated from the IP address ".$_SERVER['REMOTE_ADDR']." to server ".gethostname()."\n".file_get_contents($file);
		if(strpos($contents,"ERROR")===true) {
			$headers = "MIME-Version: 1.0\n" ;
	        $headers .= "Content-Type: text/plain; charset=\"UTF-8\"\n";
			$headers .= "X-Priority: 1 (Highest)\n";
			$headers .= "X-MSMail-Priority: High\n";
			$headers .= "Importance: High\n";
			$hasError = true;
		} else {
			$hasError = false;
			$headers = null;
		}
		$subject = ($hasError?"ERROR ":"SUCCESS ")." LOG FOR ".$productname." ".basename($file)." FROM MACHINE ".$machineid;
		$subscribers = $array = preg_split ('/$\R?^/m', file_get_contents(relative_to_absolute($target_base."subscribers.txt")));
		foreach($subscribers as $subscriber) {
			$i = strpos($subscriber,"=");
			$to = trim(substr($subscriber,0,$i));
			$crit = substr($subscriber,$i);
			if(!(strpos($crit,"log")===false)||(!(strpos($crit,"err")===false)&& hasError)) {
				mail($to,$subject,$contents,$headers);
			}
		}
		$movetarget = $target_base."sent";
		if(!is_dir($movetarget))
			mkdir($movetarget);
		$movetarget .= "/".basename($file);
		file_put_contents($movetarget,$contents,FILE_APPEND|LOCK_EX);
		unlink($file);
	}
}
// The $file in the temp directory has been uploaded to be placed in the product log directory
function log_upload($tempfile,$destination,$productname,$machineid,$version)
{
	$target = "";
	if($productname!=null)
		$target = io_get_productdir($productname,$version).'/';
	$target .= 'logs/';
	if(!is_dir($target))
		mkdir($target,0777,true);
	$target .= $destination;
	if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
		echo "ok:0:The log file $destination has been uploaded to $target";
	}
}
function io_get_productdir($productname,$version)
{
	$path='products';
	if($productname!=null)
		$path.='/'.$productname;
	if($version!=null)
		$path.='/v'.str_replace('.','_',$version);
	return $path;
}
function log_get_dir()
{
	return dirname($_SERVER['SCRIPT_NAME']).'/logs';
}
function log_system_messge($line,$send)
{
	error_log(date("h:i")." : ".$line."\n",3,"logs/".date("Ymd").".log");
}

function log_system_warning($line)
{
	log_system_message("WARNING: ".$line);
}

function log_system_error($line)
{
	log_system_message("ERROR: ".$line);
}

function relative_to_absolute($path)
{
	return 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/' . $path;
}

?>